package com.platform.api.bzproject.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.github.pagehelper.PageInfo;
import com.platform.api.bzproject.dto.UserMoney;
import com.platform.api.bzproject.model.*;
import com.platform.api.bzproject.service.*;
import com.platform.common.core.Constant;
import com.platform.common.core.Result;
import com.platform.common.core.ResultCode;
import com.platform.security.util.SecurityUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 源码联系微信：2549789059
 * <p>
 * 余额记录表 前端控制器
 * </p>
 *
 * @author guoshao
 * @since 2021-10-29
 */
@RestController
@RequestMapping("{appid}/p/balance")
public class BalanceRecordController {

    @Autowired
    private IBalanceRecordService iBalanceRecordService;


    @Autowired
    private IDistributionProfitService iDistributionProfitService;


    @Autowired
    private UserService userService;

    @Autowired
    private IWithdrawalDetailsService iWithdrawalDetailsService;


    @GetMapping("profit")
    public Result profit(BalanceRecord balanceRecord){

        DistributionProfit distributionProfit = new DistributionProfit();
        distributionProfit.setStatus(1);

        Map<String,Object> map = new HashMap<>();
        balanceRecord.setDataType(1);
        balanceRecord.setStatus(1);

        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
            if(StringUtils.isNotBlank(userId)){
                balanceRecord.setUserId(userId);
                distributionProfit.setUserId(userId);
            }
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"获取用户信息失败");
        }

        int count = iBalanceRecordService.count(new QueryWrapper<BalanceRecord>()
                .eq("user_id", balanceRecord.getUserId())
                .eq("status", 1).eq("data_type", 1));
        map.put("count",count);
        //map.put("settled",iBalanceRecordService.selectSumMoney(balanceRecord));

        //已结算 收益
        balanceRecord.setStatus(2);
        map.put("toSettled",iBalanceRecordService.selectSumMoney(balanceRecord));
        //已打款 收益
        balanceRecord.setStatus(3);
        map.put("paid",iBalanceRecordService.selectSumMoney(balanceRecord));

        //奖励 次数
        int rewardCount = iDistributionProfitService.count(new QueryWrapper<DistributionProfit>()
                .eq("user_id", balanceRecord.getUserId())
                .eq("status", 1));
        map.put("rewardCount",rewardCount);

        //奖励已结算
        distributionProfit.setStatus(2);
        BigDecimal rewardSett = iDistributionProfitService.selectSumMoney(distributionProfit);
        map.put("rewardSett",rewardSett);

        //奖励 已打款
        distributionProfit.setStatus(3);
        BigDecimal rewardPay = iDistributionProfitService.selectSumMoney(distributionProfit);
        map.put("rewardPay",rewardPay);


        //=====================================获取收益数据=================================
        //总收益
        balanceRecord.setStatus(null);
        balanceRecord.setDataType(null);
        distributionProfit.setStatus(null);
        BigDecimal sumMoney = iBalanceRecordService.selectSumMoney(balanceRecord);
        distributionProfit.setStatus(null);
        BigDecimal disSumMoney = iDistributionProfitService.selectSumMoney(distributionProfit);

        //不做四舍五入
        map.put("sumMoney",sumMoney.add(disSumMoney));

        //昨日收益
        balanceRecord.setCreateTime(new Date());
        BigDecimal yesterdayMoney = iBalanceRecordService.selectSumMoney(balanceRecord);
        distributionProfit.setCreateTime(new Date());
        BigDecimal disDayMoney = iDistributionProfitService.selectSumMoney(distributionProfit);
        map.put("yesterdayMoney",yesterdayMoney.add(disDayMoney));

        //当月收入
        List<BigDecimal> thisMonth = iBalanceRecordService.thisMonth(balanceRecord);
        map.put("thisMonth",thisMonth.get(0).add(thisMonth.get(1)));

        //上月收入
        List<BigDecimal> lastMonth = iBalanceRecordService.lastMonth(balanceRecord);
        map.put("lastMonth",lastMonth.get(0).add(lastMonth.get(1)));


        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("userId",userId);
        //总下载
        map.put("sumDownCount",iBalanceRecordService.getDownCount(queryMap));
        //今日下载
        queryMap.put("today",1);
        map.put("toNowDownCount",iBalanceRecordService.getDownCount(queryMap));
        //昨日下载
        queryMap.put("today",2);
        map.put("toDayDownCount",iBalanceRecordService.getDownCount(queryMap));

        return Result.success(map);
    }

    @GetMapping("centerProfit")
    public Result centerProfit(BalanceRecord balanceRecord){
        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
            if(StringUtils.isNotBlank(userId)){
                balanceRecord.setUserId(userId);
            }
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"获取用户信息失败");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("sumMoney",iBalanceRecordService.selectSumMoney(balanceRecord));
        balanceRecord.setCreateTime(new Date());
        map.put("yesterdayMoney",iBalanceRecordService.selectSumMoney(balanceRecord));
        return Result.success(map);
    }

    @GetMapping("/list")
    public Result select(BalanceRecord balanceRecord,Integer offset){

        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
            if(StringUtils.isNotBlank(userId)){
                balanceRecord.setUserId(userId);
            }
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"获取用户信息失败");
        }

        PageInfo<BalanceRecord> pageInfo = iBalanceRecordService.selectBalanceRecordList(balanceRecord, offset);

        return Result.success(pageInfo);
    }


    /**
     * 查看用户收益信息  提现金额，余额，到账金额
     */
    @GetMapping("/userInfoBal")
    public Result userInfoBal() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getUserByUserId(userId);

        UserMoney userDto = new UserMoney();
        userDto.setBalance(null == user.getBalance() ? new BigDecimal("0") : user.getBalance());
        userDto.setFrozenBalance(user.getFrozenBalance());


        //查询用户收益记录
        BalanceRecord balanceRecord = new BalanceRecord();
        balanceRecord.setUserId(userId);

        DistributionProfit distributionProfit = new DistributionProfit();
        distributionProfit.setUserId(userId);

        //即将到账
        balanceRecord.setStatus(2);
        BigDecimal arrivalSoon = iBalanceRecordService.selectSumMoney(balanceRecord);
        distributionProfit.setStatus(2);
        BigDecimal aDouble = iDistributionProfitService.selectSumMoney(distributionProfit);
        userDto.setArrivalSoon(arrivalSoon.add(aDouble));

        //累计到账
        balanceRecord.setStatus(3);
        BigDecimal sumArrival = iBalanceRecordService.selectSumMoney(balanceRecord);
        distributionProfit.setStatus(3);
        BigDecimal aDouble1 = iDistributionProfitService.selectSumMoney(distributionProfit);

        userDto.setSumArrival(sumArrival.add(aDouble1));

        //累计提现
        BigDecimal withdrawal = iWithdrawalDetailsService.selectSumMoney(userId);
        userDto.setSumWithdrawal(null == withdrawal ? userDto.getSumWithdrawal() : withdrawal);

        return Result.success(userDto);
    }

    @GetMapping("/listNew")
    public Result listNew(BalanceRecord balanceRecord,Integer offset){

        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
            if(StringUtils.isNotBlank(userId)){
                balanceRecord.setUserId(userId);
            }
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"获取用户信息失败");
        }

        PageInfo<BalanceRecord> pageInfo = iBalanceRecordService.selecttBalanceRecordListNew(balanceRecord, offset);
        return Result.success(pageInfo);
    }

}
